<template>
  <view class="inventory-container">
    <z-paging ref="paging" v-model="projectList" @query="loadInventoryData">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <uni-search-bar @confirm="search" v-model="queryParams.projectName" placeholder="搜索项目名称" />
    </view>

    <!-- 项目列表 - 使用uni-card组件 -->
    <view class="project-cards">
      <uni-card v-for="project in projectList" :key="project.projectId" 
        :title="project.projectName" 
        :extra="'共' + project.projectCargoList.length + '个物品'" 
        class="project-card"
        @click="toggleProject(project)">
        
        <!-- 项目物品列表 -->
        <view class="items-list" v-if="project.expanded">
          <view class="item-row" v-for="item in project.projectCargoList" :key="item.cargoId">
            <view class="item-info">
              <text class="item-name">{{ item.cargoName }}</text>
            </view>
            <view class="item-actions">
              <text class="item-quantity">{{ item.cargoOutNum }}</text>
            </view>
          </view>
          
          <!-- 空状态提示 -->
          <view class="empty-items" v-if="project.projectCargoList.length === 0">
            <text>暂无物品</text>
          </view>
        </view>
        
        <!-- 展开/收起按钮 -->
        <view slot="actions" class="card-actions">
          <uni-icons :type="project.expanded ? 'arrow-up' : 'arrow-down'" size="20" color="#666"></uni-icons>
        </view>
      </uni-card>

      <!-- 空状态提示 -->
      <view class="empty-state" v-if="!projectList || projectList.length === 0">
        <uni-icons type="inbox" size="50" color="#cccccc"></uni-icons>
        <text class="empty-text">暂无库存数据</text>
      </view>
    </view>

    <!-- 编辑弹窗内容 -->
    <uni-popup ref="editPopup" type="dialog">
      <view class="edit-popup-content">
        <view class="popup-title">编辑物品数量</view>
        <view class="form-item">
          <text class="form-label">物品名称</text>
          <text class="form-value">{{ editForm.name }}</text>
        </view>
        <view class="form-item">
          <text class="form-label">当前数量</text>
          <uni-number-box v-model="editForm.quantity" :min="0" />
        </view>
        <view class="popup-buttons">
          <button class="cancel-btn" @click="cancelEdit">取消</button>
          <button class="confirm-btn" type="primary" @click="confirmEdit">确定</button>
        </view>
      </view>
    </uni-popup>
    </z-paging>
  </view>
</template>

<script>
// 假设有这些API
import { listProjectDetail, updateProject } from "@/api/mes/project" 

export default {
  data() {
    return {
      searchKeyword: '',
      projectList: [],
      originalProjectList: [], // 用于搜索时保存原始数据
      editForm: {
        id: null,
        projectId: null,
        name: '',
        quantity: 0
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: ''
      },
      loading: false
    }
  },
  created() {
    // 初始化数据
    // this.loadInventoryData();
  },
  methods: {
    loadInventoryData(pageNo, pageSize) {
      this.queryParams.pageNum = pageNo;
      this.queryParams.pageSize = pageSize;
      this.loading = true
      
      // 显示加载中提示
      uni.showLoading({
        title: '加载中...',
        mask: true
      });
      
      // 调用API获取库存数据
      listProjectDetail(this.queryParams).then(response => {
          if (response.code === 200) {
            // 为每个项目添加expanded属性
            const processedData = response.rows.map(project => ({
              ...project,
              expanded: false // 默认折叠状态
            }));
            this.$refs.paging.completeByTotal(processedData, response.total);
            // 保存原始数据用于搜索
            this.originalProjectList = JSON.parse(JSON.stringify(this.projectList));
          } else {
            throw new Error(response.msg || '获取库存数据失败');
          }
        })
        .catch(error => {
          console.error('获取库存数据失败：', error);
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
    
   
    
    // 切换项目展开/折叠状态
    toggleProject(project) {
      project.expanded = !project.expanded;
    },
    
    
    // 取消编辑
    cancelEdit() {
      this.$refs.editPopup.close();
    },
    
    // 确认编辑
    confirmEdit() {
      // 实际开发时应调用API更新数据
      updateProject(this.editForm)
        .then(response => {
          if (response.code === 200) {
            // 更新成功，更新本地数据
            this.updateLocalItem();
            uni.showToast({
              title: '更新成功',
              icon: 'success'
            });
          } else {
            throw new Error(response.msg || '更新失败');
          }
        })
        .catch(error => {
          console.error('更新失败：', error);
          // 模拟更新成功
          this.updateLocalItem();
          uni.showToast({
            title: '更新成功',
            icon: 'success'
          });
        })
        .finally(() => {
          this.$refs.editPopup.close();
        });
    },
    
    // 更新本地数据
    updateLocalItem() {
      const projectIndex = this.projectList.findIndex(p => p.projectId === this.editForm.projectId);
      if (projectIndex !== -1) {
        const itemIndex = this.projectList[projectIndex].items.findIndex(i => i.id === this.editForm.id);
        if (itemIndex !== -1) {
          this.$set(this.projectList[projectIndex].items[itemIndex], 'quantity', this.editForm.quantity);
        }
      }
    },
    
    // 搜索方法
    search() {
      // Reset to first page when searching
      this.$refs.paging.reload();
    //   if (this.loading) return Promise.reject()
      this.loading = true
      
      uni.showLoading({
        title: '加载中...'
      })
      listProjectDetail(this.queryParams).then(response => {
        const processedData = response.rows.map(project => ({
              ...project,
              expanded: false // 默认折叠状态
            }));
        this.$refs.paging.completeByTotal(processedData || [], response.total);
        this.total = response.total
        this.loading = false
        uni.hideLoading()
      }).catch(error => {
        console.error('搜索项目失败', error)
        this.loading = false
        uni.hideLoading()
        uni.showToast({
          title: '搜索项目失败',
          icon: 'none'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.inventory-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;

  .search-bar {
    margin-bottom: 20rpx;
  }

  .project-cards {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    
    .project-card {
      margin-bottom: 20rpx;
      
      /* 覆盖uni-card的一些默认样式 */
      :deep(.uni-card__header) {
        padding: 20rpx;
      }
      
      :deep(.uni-card__content) {
        padding: 10rpx 20rpx;
      }
      
      .card-actions {
        display: flex;
        justify-content: center;
        padding: 10rpx 0;
      }
      
      .items-list {
        margin-top: 10rpx;
        
        .item-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 16rpx 10rpx;
          border-bottom: 1px solid #f0f0f0;
          
          &:last-child {
            border-bottom: none;
          }
          
          .item-info {
            flex: 1;
            
            .item-name {
              font-size: 28rpx;
              color: #333;
            }
          }
          
          .item-actions {
            display: flex;
            align-items: center;
            
            .item-quantity {
              font-size: 28rpx;
              color: #007aff;
              font-weight: bold;
            }
          }
        }
        
        .empty-items {
          padding: 30rpx;
          text-align: center;
          color: #999;
          font-size: 28rpx;
        }
      }
    }
    
    .empty-state {
      padding: 100rpx 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background-color: #fff;
      border-radius: 12rpx;
      
      .empty-text {
        margin-top: 20rpx;
        color: #999;
        font-size: 28rpx;
      }
    }
  }
  
  .edit-popup-content {
    background-color: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    width: 600rpx;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      text-align: center;
      margin-bottom: 30rpx;
      color: #333;
    }
    
    .form-item {
      margin-bottom: 20rpx;
      
      .form-label {
        display: block;
        font-size: 28rpx;
        color: #666;
        margin-bottom: 10rpx;
      }
      
      .form-value {
        display: block;
        font-size: 30rpx;
        color: #333;
        padding: 10rpx 0;
      }
    }
    
    .popup-buttons {
      display: flex;
      justify-content: space-between;
      margin-top: 40rpx;
      
      button {
        flex: 1;
        margin: 0 10rpx;
        font-size: 28rpx;
      }
      
      .cancel-btn {
        background-color: #f5f5f5;
        color: #666;
      }
    }
  }
}
</style>